// 创建用户相关
import { defineStore } from 'pinia'
// 引入接口
import { reqLogin, reqUserInfo } from '@/api/user'
// 引入数据类型
import type {
  loginForm,
  loginResponseData,
  userResponseData,
} from '@/api/user/type'
import type { UserState } from './types/type'
// 引入本地存储的工具方法
import {
  SET_TOKEN,
  GET_TOKEN,
  SET_USER_INFO,
  GET_USER_INFO,
  REMOVE_TOKEN_USER_INFO
} from '@/utils/token'
// 引入路由 （常量）
import { constantRoute } from '@/router/routes'

const useUserStore = defineStore('User', {
  // 存储数据
  state: (): UserState => {
    return {
      token: GET_TOKEN(), // 用户的唯一标识
      menuRouts: constantRoute, // 菜单数组 (路由)
      username: GET_USER_INFO().username, // 用户名称
      avatar: GET_USER_INFO().avatar, // 用户头像
      roles: []
    }
  },
  // 异步|逻辑
  actions: {
    // 登录接口 返回 token username (用户名称) avatar (用户头像)
    async userLogin(data: loginForm) {
      const result: loginResponseData = await reqLogin(data)
      if (result.code === 200) {
        // pinia 仓库存储一下 token  断言 (result.data.token as string)
        this.token = result.data.token as string
        // 本地存储持久化存储一份
        SET_TOKEN(result.data.token as string)
        // 存储用户名称与头像
        this.username = result.data.checkUser.username
        this.avatar = result.data.checkUser.avatar
        // 本地持久化 存储一份用户名称与用户头像
        SET_USER_INFO(
          result.data.checkUser.username as string,
          result.data.checkUser.avatar as string,
        )
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data.message))
      }
    },
    // 用户信息接口
    async userInfo() {
      return new Promise((resolve, reject) => {
        reqUserInfo().then(res => {
          const result: userResponseData = res
          if (result.code === 200) {
            this.roles = result.data.checkUser.roles
            this.username = result.data.checkUser.username
            this.avatar = result.data.checkUser.avatar
            // 本地持久化 存储一份用户名称与用户头像
            SET_USER_INFO(
              result.data.checkUser.username as string,
              result.data.checkUser.avatar as string,
            )
          }
          resolve(result)
        }).catch(error => {
          reject(error)
        })
      })
      // const result: userResponseData = await reqUserInfo()
      // if (result.code === 200) {
      //   this.username = result.data.checkUser.username
      //   this.avatar = result.data.checkUser.avatar
      //   // 本地持久化 存储一份用户名称与用户头像
      //   SET_USER_INFO(
      //     result.data.checkUser.username as string,
      //     result.data.checkUser.avatar as string,
      //   )
      // }
    },
    // 退出登录
    userLogout() {
      // 目前没有退出登录的接口，清除 token 用户信息
      this.token = ''
      this.username = ''
      this.avatar = ''
      this.roles = []
      REMOVE_TOKEN_USER_INFO()
    }
  },
  getters: {
    getUserName: (state) => state.username,
  },
})

// 对外暴露
export default useUserStore
